import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import * as path from 'node:path'
import * as fs from 'node:fs'

let mainWindow = null
let consoleWindow = null
function createWindow() {
  mainWindow = new BrowserWindow({
    minWidth: 660, //设置窗口最小宽度(单位:像素)
    minHeight: 430, //设置窗口最小宽度(单位:像素)
    width: 850,
    height: 600,
    show: false,
    frame: false,
    movable: true,
    title: '计时器',
    autoHideMenuBar: false, //自动隐藏菜单栏
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: path.resolve(__dirname, '../preload/index.js'),
      contextIsolation: true,
      nodeIntegration: false,
      enableRemoteModule: false,
      webSecurity: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    console.log(process.env['ELECTRON_RENDERER_URL'])
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // 进程通信接收
  ipcMain.on('close-window', closeWindow)

  ipcMain.on('min-window', minWindow)

  ipcMain.on('create-back-window', createBackWindow)

  ipcMain.on('create-time-window', createTimeWindow)

  // 主窗口最小化窗口方法
  function minWindow() {
    mainWindow.minimize()
  }

  // 主窗口关闭窗口方法
  function closeWindow() {
    mainWindow.close()
    if (consoleWindow !== null) {
      consoleWindow.close()
    }
  }

  //创建背景展示页面
  function createBackWindow() {
    const win = new BrowserWindow({
      width: 800,
      height: 600,
      frame: true,
      autoHideMenuBar: true, //自动隐藏菜单栏
      webPreferences: {
        preload: join(__dirname, '../preload/index.js')
      }
    })

    // 构建本地文件的绝对路径
    const indexPath = path.join(__dirname, '../renderer/index_background.html')

    ipcMain.on('get-message-toBack', () => mainWindow.webContents.send('reqMessage-to-console'))

    ipcMain.on('resMessage-back-main', (event, data) => {
      try {
        if (win) {
          win.webContents.send('resMessage-to-back', data)
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    })

    ipcMain.on('back-full-screen', () => {
      try {
        if (win) {
          //进入全屏时隐藏窗口边框
          win.setAutoHideMenuBar(false)
          win.setFullScreen(true)
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    })

    ipcMain.on('back-noFull-screen', () => {
      try {
        if (win) {
          //进入全屏时隐藏窗口边框
          win.setAutoHideMenuBar(true)
          win.setFullScreen(false)
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    })

    // 加载本地页面
    win.loadFile(indexPath)
  }

  //创建计时展示页面
  function createTimeWindow() {
    const win = new BrowserWindow({
      width: 900,
      height: 600,
      minWidth: 900,
      minHeight: 600,
      frame: true,
      autoHideMenuBar: true, //自动隐藏菜单栏
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        nodeIntegration: false,
        contextIsolation: true,
        webSecurity: true
      }
    })

    const indexPath = path.join(__dirname, '../renderer/index_time.html')

    ipcMain.on('stopOrStart-show-time', stopOrStart)

    ipcMain.on('reqMessage-from-console', () =>
      // 发送请求('getMessage-to-console')
      mainWindow.webContents.send('reqMessage-to-console')
    )

    ipcMain.on('resMessage-back-main', (event, data) => {
      try {
        if (win) {
          win.webContents.send('resMessage-to-time', data)
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    })

    ipcMain.on('time-full-screen', () => {
      try {
        if (win) {
          //进入全屏时隐藏窗口边框
          win.setAutoHideMenuBar(false)
          win.setFullScreen(true)
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    })

    ipcMain.on('time-noFull-screen', () => {
      try {
        if (win) {
          //进入全屏时隐藏窗口边框
          win.setAutoHideMenuBar(true)
          win.setFullScreen(false)
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    })

    // 按钮更改Time展示值
    ipcMain.on('changeInfo-from-console', (event, data) => {
      try {
        if (win) {
          win.webContents.send('changeInfo-to-time', data)
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    })

    //接受时间并传给Time
    ipcMain.on('time-from-console', (event, data) => {
      try {
        if (win) {
          win.webContents.send('time-to-time', data)
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    })

    // 暂停或继续展示计时
    function stopOrStart() {
      try {
        if (win) {
          win.webContents.send('stopOrStart-show-time')
        }
      } catch (error) {
        console.log('Window has been closed')
      }
    }

    // 加载本地页面
    win.loadFile(indexPath)
  }
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  initializeRoomList()
  //创建主窗口
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 监听来自渲染进程的保存数据请求
const roomListFilePath = path.join(app.getPath('documents'), '/data', 'roomList.json')

async function initializeRoomList() {
  const projectDataPath = path.join(app.getPath('documents'), '/data')

  // 确保 data 文件夹存在
  if (!fs.existsSync(projectDataPath)) {
    fs.mkdirSync(projectDataPath)
  }

  // 检查 roomList.json 是否存在
  if (!fs.existsSync(roomListFilePath)) {
    // 如果不存在，创建一个空的 roomList.json
    await fs.promises.writeFile(roomListFilePath, JSON.stringify([], null, 2), 'utf-8')
  }
}

const counterFilePath = path.join(app.getPath('documents'), '/data', 'counter.json') // 计数器文件路径

ipcMain.handle('save-room', async (event, data) => {
  try {
    // 读取现有的 roomList 数据
    let roomList = []
    if (fs.existsSync(roomListFilePath)) {
      const data = await fs.promises.readFile(roomListFilePath, 'utf8')
      roomList = JSON.parse(data)

      // 确保 roomList 是一个数组
      if (!Array.isArray(roomList)) {
        console.warn('roomList is not an array, converting to array')
        roomList = [roomList]
      }
    }

    // 添加 id 字段到数据对象
    let i = await readCounter()
    i += 1
    data.id = i

    // 将新数据追加到 roomList 中
    roomList.push(data)

    // 写入更新后的 roomList 数据
    await fs.promises.writeFile(roomListFilePath, JSON.stringify(roomList, null, 2), 'utf-8')

    // 更新计数器
    await writeCounter(i)

    return { success: true }
  } catch (err) {
    console.error('Error saving room:', err)
    return { success: false, error: err.message }
  }
})

async function readCounter() {
  try {
    const data = await fs.promises.readFile(counterFilePath, 'utf-8')
    return JSON.parse(data).count
  } catch (err) {
    // 如果文件不存在或解析失败，返回0
    return 0
  }
}
async function writeCounter(count) {
  try {
    const counterObject = { count }
    await fs.promises.writeFile(counterFilePath, JSON.stringify(counterObject, null, 2), 'utf-8')
  } catch (err) {
    console.error('Error writing counter file', err)
  }
}
//获取data列表
ipcMain.handle('get-room-list', async (event, roomId) => {
  try {
    if (!fs.existsSync(roomListFilePath)) {
      return { success: true, data: [] }
    }

    const data = await fs.promises.readFile(roomListFilePath, 'utf8')
    const roomList = JSON.parse(data)

    // 如果传入了 roomId，则根据 id 查找对应的房间
    if (roomId) {
      const room = roomList.find((item) => item.id === Number(roomId))
      if (!room) {
        return { success: false, error: 'Room not found' }
      }
      console.log(123, room)
      return { success: true, data: [room] }
    }

    return { success: true, data: roomList }
  } catch (err) {
    console.error('Error getting room list:', err)
    return { success: false, error: err.message }
  }
})

//根据文件删除json文件
ipcMain.handle('delete-room', async (event, roomId) => {
  try {
    // 读取现有的 roomList 数据
    let roomList = []
    if (fs.existsSync(roomListFilePath)) {
      const data = await fs.promises.readFile(roomListFilePath, 'utf8')
      roomList = JSON.parse(data)

      // 确保 roomList 是一个数组
      if (!Array.isArray(roomList)) {
        console.warn('roomList is not an array, converting to array')
        roomList = [roomList]
      }
    }

    // 查找要删除的房间
    const index = roomList.findIndex((room) => room.id === roomId)
    if (index === -1) {
      return { success: false, error: 'Room not found' }
    }

    // 删除房间
    roomList.splice(index, 1)

    // 写入更新后的 roomList 数据
    await fs.promises.writeFile(roomListFilePath, JSON.stringify(roomList, null, 2), 'utf-8')

    return { success: true }
  } catch (err) {
    console.error('Error deleting room:', err)
    return { success: false, error: err.message }
  }
})

// 定义主进程中的变量
const mainProcessVariable = {
  path: path.join(app.getPath('documents'), '/data'),
  dirname: __dirname
}

// 处理来自渲染进程的IPC请求
ipcMain.handle('getMainProcessVariable', () => {
  return mainProcessVariable
})

// 获取用户文档目录
// const userDataPath = app.getPath('documents')
// console.log(123, userDataPath)

// // 或者获取应用数据目录
// const appDataPath = app.getPath('appData')
// console.log(321, appDataPath)
